﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

using ChiDao.Component.Utils;
using ChiDao.Business.Models;
using ChiDao.Business.Models.Account;
using ChiDao.Site.Models;
using ChiDao.Business.Data.Repositories.Account;
using ChiDao.Business.Data.Repositories.Security;
using ChiDao.Business.Models.Security;
using ChiDao.Business.Service.CommonSupport;

namespace ChiDao.Business.Service.Impl
{
    /// <summary>
    ///     账户模块站点业务实现
    /// </summary>
    [Export(typeof(IAccountService))]
    internal class AccountService : IAccountService
    {

        #region 属性

        #region 受保护的属性

        /// <summary>
        /// 获取或设置 用户信息数据访问对象
        /// </summary>
        [Import]
        protected IPersonRepository PersonRepository { get; set; }

        /// <summary>
        /// 获取或设置 用户扩展信息数据访问对象
        /// </summary>
        [Import]
        protected IPersonExtendRepository PersonExtendRepository { get; set; }

        /// <summary>
        /// 获取或设置 登录记录信息数据访问对象
        /// </summary>
        [Import]
        protected ILoginLogRepository LoginLogRepository { get; set; }

        /// <summary>
        /// 获取或设置 角色信息业务访问对象
        /// </summary>
        //[Import]
        //protected IRoleRepository RoleRepository { get; set; }

        [Import]
        protected IMenuInfoRepository MenuInfoRepository { get; set; }

        [Import]
        protected IActionInfoRepository ActionInfoRepository { get; set; }

        #endregion

        #region 公共属性

        /// <summary>
        /// 获取 用户信息查询数据集
        /// </summary>
        public IQueryable<Person> Persons
        {
            get { return PersonRepository.Entities; }
        }

        /// <summary>
        /// 获取 用户扩展信息查询数据集
        /// </summary>
        public IQueryable<PersonExtend> PersonExtends
        {
            get { return PersonExtendRepository.Entities; }
        }

        /// <summary>
        /// 获取 登录记录信息查询数据集
        /// </summary>
        public IQueryable<LoginLog> LoginLogs
        {
            get { return LoginLogRepository.Entities; }
        }

        /// <summary>
        /// 获取 角色信息查询数据集
        /// </summary>
        //public IQueryable<Role> Roles
        //{
        //    get { return RoleRepository.Entities; }
        //}

        public IQueryable<MenuInfo> MenuInfoes
        {
            get { return MenuInfoRepository.Entities; }
        }

        public IQueryable<ActionInfo> ActionInfoes
        {
            get { return ActionInfoRepository.Entities; }
        }

        #endregion

        #endregion

        /// <summary>
        ///     用户登录
        /// </summary>
        /// <param name="model">登录模型信息</param>
        /// <returns>业务操作结果</returns>
        public OperationResult Login(LoginModel model)
        {
            PublicHelper.CheckArgument(model, "model");
            //LoginInfo loginInfo = new LoginInfo
            //{
            //    Account = model.Account,
            //    Password = model.Password,
            //    IpAddress = HttpContext.Current.Request.UserHostAddress
            //};

            OperationResult result = this.LoginOperation(model);

            if (result.ResultType == OperationResultType.Success)
            {
                Person member = (Person)result.AppendData;
                DateTime expiration = model.IsRememberLogin
                    ? DateTime.Now.AddDays(7)
                    : DateTime.Now.Add(FormsAuthentication.Timeout);
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, member.UserName, DateTime.Now, expiration,
                    true, member.NickName, FormsAuthentication.FormsCookiePath);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                if (model.IsRememberLogin)
                {
                    cookie.Expires = DateTime.Now.AddDays(7);
                }
                HttpContext.Current.Response.Cookies.Set(cookie);
                result.AppendData = null;

                SystemData.Instance.CurrentUser = member;
                SystemData.Instance.MenuInfoes = MenuInfoes.ToList();
                SystemData.Instance.ActionInfoes = ActionInfoes.ToList();
            }
            return result;
        }

        private OperationResult LoginOperation(LoginModel loginInfo)
        {
            PublicHelper.CheckArgument(loginInfo, "loginInfo");
            Person member = PersonRepository.Entities.SingleOrDefault(m => m.UserName == loginInfo.Account || m.Email == loginInfo.Account);
            if (member == null)
            {
                return new OperationResult(OperationResultType.QueryNull, "指定账号的用户不存在。");
            }
            if (member.Password != EncryptHelper.ToMD5Salt(loginInfo.Password))  //MD5盐值加密
            {
                return new OperationResult(OperationResultType.Warning, "登录密码不正确。");
            }
            LoginLog loginLog = new LoginLog { IpAddress = loginInfo.IpAddress, Person = member };
            LoginLogRepository.Insert(loginLog);
            return new OperationResult(OperationResultType.Success, "登录成功。", member);
        }

        /// <summary>
        ///     用户退出
        /// </summary>
        public void Logout()
        {
            FormsAuthentication.SignOut();
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        public OperationResult Add(PersonView view)
        {
            PublicHelper.CheckArgument(view, "view");

            Person model = new Person();
            model.UserName = view.UserName;
            model.NickName = view.NickName;
            model.Password = view.Password;
            model.Email = view.Email;
            //model.Extend.Tel = view.Extend.Tel;
            //model.Extend.Address = view.Extend.Address;
            model.IsDeleted = view.IsDeleted;

            if (PersonRepository.Insert(model, true) > 0)
            {
                return new OperationResult(OperationResultType.Success, "新增成功", model);
            }
            else
            {
                return new OperationResult(OperationResultType.Warning, "新增失败，请检查");
            }
        }
    }
}